<?php

namespace app\api\service;

use app\model\Money;
use think\facade\Cache;
use app\model\PayRecord;
use app\model\Link;
use app\model\RechargeTemplate;
use app\model\Applet;
use app\model\MountedAppletCustomRechargeConfig;
use app\model\CustomRechargeTemplate;

class TopUpService
{
    private $moneyModel;
    private $payRecordModel;
    private $linkModel;
    private $rechargeTemplateModel;
    private $appletModel;
    private $mountedAppletCustomRechargeConfigModel;
    private $customRechargeTemplateModel;

    public function __construct(Money $moneyModel, PayRecord $payRecordModel, Link $linkModel, RechargeTemplate $rechargeTemplateModel, Applet $appletModel, MountedAppletCustomRechargeConfig $mountedAppletCustomRechargeConfigModel, CustomRechargeTemplate $customRechargeTemplateModel)
    {
        $this->moneyModel = $moneyModel;
        $this->payRecordModel = $payRecordModel;
        $this->linkModel = $linkModel;
        $this->rechargeTemplateModel = $rechargeTemplateModel;
        $this->appletModel = $appletModel;
        $this->mountedAppletCustomRechargeConfigModel = $mountedAppletCustomRechargeConfigModel;
        $this->customRechargeTemplateModel = $customRechargeTemplateModel;
    }

    /**
     * 获取充值套餐数据
     * 
     * @dateTime 2022/09/05
     * @author zhixiang0215@126.com
     * @return array
     */
    public function getTopUpPackage($token,$params = [])
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(8);
        $linkIdKey = config('redis_key.api.user_login_link_id');
        $linkId = $redis->get($linkIdKey . $token);
        $userId = $redis->get($token);
        $mountKey = config('redis_key.api.user_login_mount_key').$userId;
        $mountPlatform = $redis->get($mountKey);

        $data = [];
        //测试用户使用低充模板
        if ($userId == 4443885 || $userId == 8886539 || $userId == 8255755 || $userId == 4372084 || $userId == 9042417 || $userId == 4371875 || $userId == 9219477 || $userId == 9094460) {
            $rechargeTemplateData = $this->rechargeTemplateModel->getInfoByWhere(['id' => 361], 'recharged_content, not_recharged_content');
            $data = json_decode($rechargeTemplateData['recharged_content'], true);
            $data = json_decode($data, true);
            return $data;
        }

        if ($linkId) {
            $linkData = $this->linkModel->getInfoByWhere(['id' => $linkId], 'recharge_template_id, is_new_recharge_setting');
            $rechargeData = $this->payRecordModel->getDataByWhere(['uid' => $userId, 'link_id' => $linkId, 'status' => 1], 'id');

            if (!empty($linkData['recharge_template_id'])) {
                if ($linkData['is_new_recharge_setting'] == 1) {
                    $rechargeTemplateData = $this->rechargeTemplateModel->getInfoByWhere(['id' => $linkData['recharge_template_id']], 'recharged_content, not_recharged_content');

                    if ($rechargeData && !empty($rechargeTemplateData['recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['recharged_content'], true);
                        $data = json_decode($data, true);
                    } else if (!empty($rechargeTemplateData['not_recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['not_recharged_content'], true);
                        $data = json_decode($data, true);
                    }
                } else if ($linkData['is_new_recharge_setting'] == 2) {
                    $rechargeTemplateData = $this->customRechargeTemplateModel->getInfoById($linkData['recharge_template_id'], 'recharged_content, not_recharged_content');
                    if ($rechargeData && !empty($rechargeTemplateData['recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['recharged_content'], true);
                        // $data = json_decode($data, true);
                    } else if (!empty($rechargeTemplateData['not_recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['not_recharged_content'], true);
                        // $data = json_decode($data, true);
                    }
                }

            } else {
                if ($rechargeData) {
                    $data = $this->moneyModel->getDataByWhere(['is_common' => 1, 'display_object' => 2], 'id, type, name, label, display_object, original_currency, recharge_price, send_currency, sum_currency, send_title');

                    if (!empty($data)) {
                        $data[0]['checked'] = 'checked';
                    }
                    return $data;
                } else {
                    $data = $this->moneyModel->getDataByWhere(['is_common' => 1, 'display_object' => 3], 'id, type, name, label, display_object, original_currency, recharge_price, send_currency, sum_currency, send_title');
                    if (!empty($data)) {
                        $data[0]['checked'] = 'checked';
                    }
                    return $data;
                }
            }
        } else if ($mountPlatform) {
            // 通过挂载的小程序进入的用户
            $rechargeData = $this->payRecordModel->getDataByWhere(['uid' => $userId, 'status' => 1], 'id');
            if ($mountPlatform == 1 && !empty($params['video_id'])) {
                // 抖音
                $rechargeTemplate = $this->mountedAppletCustomRechargeConfigModel->getInfoByWhere(['platform' => 1, 'video_id' => $params['video_id']], 'recharge_template_id, is_new_version');
                if ($rechargeTemplate && !empty($rechargeTemplate['is_new_version'])) {
                    // $mountVideoIdKey = config('redis_key.api.user_login_mount_video_id_key').$userId;
                    // $mountVideoIdKeyExpire = config('redis_key.api.user_login_mount_video_id_key_expire');
                    // $videoId = $redis->get($mountVideoIdKey);

                    $rechargeTemplateData = $this->customRechargeTemplateModel->getInfoByWhere(['id' => $rechargeTemplate['recharge_template_id'], 'video_id' => $params['video_id']], 'recharged_content, not_recharged_content');
                    if ($rechargeData && !empty($rechargeTemplateData['recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['recharged_content'], true);
                    } else if (!empty($rechargeTemplateData['not_recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['not_recharged_content'], true);
                    }
                } else if ($rechargeTemplate) {
                    $rechargeTemplateData = $this->rechargeTemplateModel->getInfoByWhere(['id' => $rechargeTemplate['recharge_template_id']], 'recharged_content, not_recharged_content');
                    if ($rechargeData && !empty($rechargeTemplateData['recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['recharged_content'], true);
                        $data = json_decode($data, true);
                    } else if (!empty($rechargeTemplateData['not_recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['not_recharged_content'], true);
                        $data = json_decode($data, true);
                    }
                }

            } else if ($mountPlatform == 2 && !empty($params['video_id'])) {
                // 快手
                $rechargeTemplate = $this->mountedAppletCustomRechargeConfigModel->getInfoByWhere(['platform' => 2, 'video_id' => $params['video_id']], 'recharge_template_id, is_new_version');
                if ($rechargeTemplate && !empty($rechargeTemplate['is_new_version'])) {
                    // $mountVideoIdKey = config('redis_key.api.user_login_mount_video_id_key').$userId;
                    // $mountVideoIdKeyExpire = config('redis_key.api.user_login_mount_video_id_key_expire');
                    // $videoId = $redis->get($mountVideoIdKey);

                    $rechargeTemplateData = $this->customRechargeTemplateModel->getInfoByWhere(['id' => $rechargeTemplate['recharge_template_id'], 'video_id' => $params['video_id']], 'recharged_content, not_recharged_content');
                    if ($rechargeData && !empty($rechargeTemplateData['recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['recharged_content'], true);
                    } else if (!empty($rechargeTemplateData['not_recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['not_recharged_content'], true);
                    }
                } else if ($rechargeTemplate) {
                    $rechargeTemplateData = $this->rechargeTemplateModel->getInfoByWhere(['id' => $rechargeTemplate['recharge_template_id']], 'recharged_content, not_recharged_content');
                    if ($rechargeData && !empty($rechargeTemplateData['recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['recharged_content'], true);
                        $data = json_decode($data, true);
                    } else if (!empty($rechargeTemplateData['not_recharged_content'])) {
                        $data = json_decode($rechargeTemplateData['not_recharged_content'], true);
                        $data = json_decode($data, true);
                    }
                }
            }
        } else {
            // 是否充过值
            $rechargeData = $this->payRecordModel->getDataByWhere(['uid' => $userId, 'status' => 1], 'id');

            if ($rechargeData) {
                $data = $this->moneyModel->getDataByWhere(['is_common' => 1, 'display_object' => 2,'is_display'=>1], 'id, type, name, label, display_object, original_currency, recharge_price, send_currency, sum_currency, send_title');
                if (!empty($data)) {
                    $data[0]['checked'] = 'checked';
                }
            } else {
                $data = $this->moneyModel->getDataByWhere(['is_common' => 1, 'display_object' => 3,'is_display'=>1], 'id, type, name, label, display_object, original_currency, recharge_price, send_currency, sum_currency, send_title');
                if (!empty($data)) {
                    $data[0]['checked'] = 'checked';
                }
            }
        }
        // 全部用户
        if (empty($data) || empty($data[0]) || !is_array($data[0])) {
            $data = $this->moneyModel->getDataByWhere(['is_common' => 1, 'display_object' => 1,'is_display'=>1], 'id, type, name, label, display_object, original_currency, recharge_price, send_currency, sum_currency, send_title');
            if (!empty($data)) {
                $data[0]['checked'] = 'checked';
            }
        }
        // 如果没有传video_id，代表从个人中心调起的模版,去掉解锁全集充值选项
        if (empty($params['video_id'])){
            foreach ($data as $k => &$d){
                if ($d['type'] == Money::TYPE_UNLOCK_ALL){
                    unset($data[$k]);
                }
            }
        }
        $returnData = array_values($data);
        $returnData[0]['checked'] = 'checked';
        return $returnData;
    }

    /**
     * 获取会员套餐数据
     * 
     * @dateTime 2022/09/05
     * @author zhixiang0215@126.com
     * @return json
     */
    public function getMemberPackage()
    {
        $data = $this->moneyModel->getDataByWhere(['is_common' => 1, 'type' => 2], 'name, label, display_object, original_currency, recharge_price, send_currency, sum_currency, send_title');
        return $data;
    }

    // 获取小程序配置
    public function getAppletConfig($appId)
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $appletKey = sprintf('redis_key.api.get_applet_config_%s', $appId);
        $appletJson = $redis->get($appletKey);
        if (empty($appletJson)) {
            $data = $this->appletModel->getInfoByWhere(['app_id' => $appId], 'ios_pay_switch, share_switch, name, share_img_url, template_id , activity_pay_show, virtual_pay_switch, customer_service_id, wechat_subscribe_template,is_open_ad,is_search');
//            $data['wechat_subscribe_template'] = collect($data['wechat_subscribe_template'])->column('tmplId');
            $data['sign_subscribe_template'] = collect($data['wechat_subscribe_template'])->filter(function ($item){
                return $item['tid'] == WechatSubscribeService::TYPE_SIGN_REMIND_TID ? $item : [];
            })->column('tmplId');
            $data['video_subscribe_template'] = collect($data['wechat_subscribe_template'])->filter(function ($item){
                if (in_array($item['tid'],[WechatSubscribeService::TYPE_NEW_VIDEO_ONLINE_TID,WechatSubscribeService::TYPE_VIDEO_UPDATE_TID])){
                    return $item;
                }
                return [];
            })->column('tmplId');
            unset($data['wechat_subscribe_template']);
            $redis->set($appletKey, json_encode($data), 3600);
            return $data;
        }

        $data = json_decode($appletJson, true);

        return $data;
    }

    public function getActivityPay(string $appId): array
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $appletKey = sprintf('redis_key.api.get_applet_config_%s', $appId);
        $type = config('enum.activity_pay_type', 13);
        $appletJson = $redis->get($appletKey);

        if (empty($appletJson)) {
            return [];
        }

        $applet = json_decode($appletJson ,  true);

        $activityPayShow = $applet['activity_pay_show'];

        if(!$activityPayShow){
            return [];
        }

        $data = $this->moneyModel->getInfoByWhere(['type' => $type], 'id, type, name, label, display_object, original_currency, recharge_price, send_currency, sum_currency, send_title');

        return $data;
    }
}
